package org.goldfish.demo.multifrontend.messageboard.mobile.ui.views

import android.content.Context
import android.os.Bundle
import android.util.Log
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.ElevatedButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
import org.goldfish.demo.multifrontend.messageboard.mobile.model.AddMessageRequest
import org.goldfish.demo.multifrontend.messageboard.mobile.model.MessageView
import org.goldfish.demo.multifrontend.messageboard.mobile.network.ApiClient
import org.goldfish.demo.multifrontend.messageboard.mobile.network.NetworkException
import java.time.Duration
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter

class MessageActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            MessageBoardScreen()
        }
    }
}

// Helper function to refresh messages
private suspend fun refreshMessages(
    context: Context,
    onMessagesUpdated: (List<MessageView>) -> Unit,
    onError: (Exception) -> Unit
) {
    try {
        val updatedMessages = ApiClient.getMessagesWithDefaultToken()
        onMessagesUpdated(updatedMessages)
        Log.w("MessageActivity", "refreshMessages: got messages $updatedMessages")
    } catch (e: Exception) {
        Log.e("MessageActivity", "refreshMessages: Error fetching messages", e)
        onError(e)
        NetworkException.handleApiError(
            activity = context as ComponentActivity, // Be cautious with casting here
            exception = e,
            httpErrorMessageClient = "获取消息失败: 权限不足或请求参数错误",
            httpErrorMessageServer = "获取消息失败: 服务器暂时不可用"
        )
    }
}

// Helper function to format display time (remains the same)
private fun formatDisplayTime(messageTime: LocalDateTime, formatter: DateTimeFormatter): String {
    val now = LocalDateTime.now()
    val duration = Duration.between(messageTime, now)
    return when {
        duration.toMinutes() < 1 -> "Just now"
        duration.toHours() < 1 -> "${duration.toMinutes()} minutes ago"
        duration.toHours() < 24 -> "${duration.toHours()} hours ago"
        else -> messageTime.format(formatter)
    }
}

@Composable
fun MessageItem(
    msg: MessageView,
    lastLoginTime: LocalDateTime?,
    timeFormatter: DateTimeFormatter,
    onDelete: suspend () -> Unit,
    scope: CoroutineScope,
    context: Context
) {
    val messageColor = if (lastLoginTime != null && msg.time.isAfter(lastLoginTime)) {
        MaterialTheme.colorScheme.primary
    } else {
        MaterialTheme.colorScheme.onSurface
    }

    Card(
        modifier = Modifier.fillMaxWidth(),
        shape = MaterialTheme.shapes.medium,
        elevation = CardDefaults.cardElevation(defaultElevation = 4.dp)
    ) {
        Column(modifier = Modifier.padding(12.dp)) {
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween
            ) {
                Text(
                    text = msg.sender,
                    style = MaterialTheme.typography.titleMedium
                )
                Button(
                    onClick = {
                        scope.launch {
                            try {
                                onDelete()
                            } catch (e: Exception) {
                                Log.e("MessageItem", "Error in onDelete", e)
                                NetworkException.handleApiError(
                                    activity = context as ComponentActivity,
                                    exception = e,
                                    httpErrorMessageClient = "删除失败: 权限不足，无法删除",
                                    httpErrorMessageServer = "删除失败: 服务器错误，请稍后重试"
                                )
                            }
                        }
                    },
                    colors = ButtonDefaults.buttonColors(
                        containerColor = MaterialTheme.colorScheme.error,
                        contentColor = MaterialTheme.colorScheme.onError
                    ),
                    modifier = Modifier.padding(4.dp)
                ) {
                    Text("删除")
                }
            }
            Spacer(modifier = Modifier.height(4.dp))
            Text(
                text = msg.message,
                style = MaterialTheme.typography.bodyMedium,
                color = messageColor
            )
            Spacer(modifier = Modifier.height(2.dp))
            Text(
                text = formatDisplayTime(msg.time, timeFormatter),
                style = MaterialTheme.typography.bodySmall,
                color = MaterialTheme.colorScheme.onSurfaceVariant
            )
        }
    }
}

@Composable
fun MessageInputRow(
    newMessage: String,
    onNewMessageChange: (String) -> Unit,
    onSend: suspend () -> Unit,
    scope: CoroutineScope,
    context: Context
) {
    Row(
        modifier = Modifier.fillMaxWidth(),
        horizontalArrangement = Arrangement.spacedBy(8.dp)
    ) {
        OutlinedTextField(
            value = newMessage,
            onValueChange = onNewMessageChange,
            label = { Text("写留言") },
            modifier = Modifier.weight(1f),
            maxLines = 3
        )
        ElevatedButton(
            onClick = {
                if (newMessage.isNotBlank()) {
                    scope.launch {
                        try {
                            onSend()
                        } catch (e: Exception) {
                             Log.e("MessageInputRow", "Error in onSend", e)
                            NetworkException.handleApiError(
                                activity = context as ComponentActivity,
                                exception = e,
                                httpErrorMessageClient = "发送失败: 留言内容不合法",
                                httpErrorMessageServer = "发送失败: 服务器错误，请稍后重试"
                            )
                        }
                    }
                }
            },
            modifier = Modifier.height(56.dp)
        ) {
            Text("发送")
        }
    }
}

@Composable
fun MessageBoardScreen() {
    val context = LocalContext.current
    val scope = rememberCoroutineScope()
    var messages by remember { mutableStateOf(listOf<MessageView>()) }
    var newMessage by remember { mutableStateOf("") }
    val timeFormatter = remember { DateTimeFormatter.ofPattern("MMM d, h:mm a") }
    val lastLoginTime = remember { ApiClient.lastLoginTime }

    val updateMessagesList: (List<MessageView>) -> Unit = { updatedMessages ->
        messages = updatedMessages
    }

    val handleError: (Exception) -> Unit = { exception ->
        // Generic error handling or logging at screen level if needed,
        // specific messages are handled by NetworkException.handleApiError
        Log.e("MessageBoardScreen", "An error occurred: ${exception.message}", exception)
    }

    LaunchedEffect(Unit) {
        refreshMessages(context, updateMessagesList, handleError)
    }

    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(16.dp)
    ) {
        LazyColumn(
            modifier = Modifier
                .weight(1f)
                .fillMaxWidth(),
            verticalArrangement = Arrangement.spacedBy(8.dp)
        ) {
            items(messages) { msg ->
                MessageItem(
                    msg = msg,
                    lastLoginTime = lastLoginTime,
                    timeFormatter = timeFormatter,
                    onDelete = {
                        ApiClient.deleteMessageWithDefaultToken(msg.id)
                        refreshMessages(context, updateMessagesList, handleError)
                    },
                    scope = scope,
                    context = context
                )
            }
        }

        Spacer(modifier = Modifier.height(12.dp))

        MessageInputRow(
            newMessage = newMessage,
            onNewMessageChange = { newMessage = it },
            onSend = {
                ApiClient.postMessageWithDefaultToken(
                    AddMessageRequest(
                        content = newMessage,
                        user = null
                    )
                )
                refreshMessages(context, updateMessagesList, handleError)
                newMessage = "" // Clear input after sending
            },
            scope = scope,
            context = context
        )
    }
}
